package com.tecnap.app.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import com.tecnap.R;
import com.tecnap.app.LampEntity;
import com.tecnap.app.database.LampDataSource;

public class ExportActivity extends Activity {

	private LampDataSource lampDataSource;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.export);

		// Database table "lamp" Connector
		lampDataSource = new LampDataSource(this);
	}

	public void onResume() {
		super.onResume();

		// Open connection to Database
		lampDataSource.open();
	}
	
	public void exportCsv(View v){
		// Load All the Lamps from DB
		List<LampEntity> allLamps = lampDataSource.getAllLamps();
				
		Iterator<LampEntity> it = allLamps.iterator();

		String data = "";

		while (it.hasNext()) {
			LampEntity le = it.next();
	
			data = data + le.getNumber().toString()+ ",";
			data = data + le.getPositionX() + ",";
			data = data + le.getPositionY() + ",";
			data = data + le.getType().toString() + ",";
			data = data + le.getPower().toString() + ",";
			data = data + le.getBrand().toString() + ",";
			data = data + le.getModel().toString() + ",";
			data = data + le.getComment().toString() + " \n";

		}
		//Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
		
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
		    // We can read and write the media
			File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //(Environment.DIRECTORY_DOWNLOADS);
			String dateFile = android.text.format.DateFormat.format("yyyyMMddkkmmss", new java.util.Date()).toString();

		    File file = new File(path, "GeoTecnapExport_" + dateFile + ".csv");
		    //Toast.makeText(this, path.toString(), Toast.LENGTH_SHORT).show();
		    try {
		        // Make sure the Pictures directory exists.
		        try{
		        	path.mkdirs();
		        }catch (Exception e) {
		        	e.printStackTrace();
					Toast.makeText(this, "ERROR! code:100\n "+e.getMessage(), Toast.LENGTH_SHORT).show();
				}
		        try{
		        	FileOutputStream fos = new FileOutputStream(file);
		        	 try{
				        	fos.write(data.getBytes());
				        	fos.close();
				        	try {
								AlertDialog dialog = new AlertDialog.Builder(this).create();
								dialog.setMessage("File esportato correttamente nella cartella Download \n Collegare il dispositivo al PC per scaricarlo");
								dialog.setButton(DialogInterface.BUTTON_POSITIVE,
										"Ok", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int which) {
												confirmMassRemove();
												dialog.dismiss();
											}
				
										});
								dialog.show();
							}   
						    catch (Exception e) {
								e.printStackTrace();
								Toast.makeText(this, "ERROR! code:101\n", Toast.LENGTH_SHORT).show();
							}
				     }catch (Exception e) {
				        	e.printStackTrace();
							Toast.makeText(this, "ERROR! code:103\n "+e.getMessage(), Toast.LENGTH_SHORT).show();
					}
					
		        }catch (Exception e) {
		        	e.printStackTrace();
					Toast.makeText(this, "ERROR! code:104\n "+e.getMessage(), Toast.LENGTH_SHORT).show();
				}
		       
				
		    }   
		    catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "ERROR! code:102\n" +e.getMessage() +"\n"+ path.toString() + file.toString(), Toast.LENGTH_SHORT).show();
			} 
		} else{
			//Environment.getE
			AlertDialog dialog = new AlertDialog.Builder(this).create();
			dialog.setMessage("Si è verificato un problema con la memoria interna del dispositivo. Verificare che non sia piena.");
			dialog.setButton(DialogInterface.BUTTON_POSITIVE,
					"Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog.show();
		}
		
	}

	@Override
	public void onPause() {
		super.onPause();

		// Open connection to Database
		lampDataSource.close();
	}
	
	/**
	 * This method display a confirm dialog
	 * to remove all lamps after an export
	 */
	private void confirmMassRemove() {
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Si desidera cancellare tutte le lampade \npresenti sul dispositivo?");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				"SI", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (lampDataSource.removeAll()){
							// Show a confirm dialog
							massRemoveComplete();
						}
						dialog.dismiss();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
				"NO", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}
	
	/**
	 * A simple dialog used to confirm that
	 * all lamps are removed from the database
	 */
	private void massRemoveComplete() {
		// Confirm dialog
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Cancellazione eseguita con successo!");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				"Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}
}
